package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.ErrorContext;
import com.lagou.session.ExceptionFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

@SuppressWarnings("unchecked")
public class XMLConfigBuilder {

    private InputStream inputStream;
    private Configuration configuration;

    public XMLConfigBuilder(InputStream inputStream){
        this.inputStream = inputStream;
        configuration = new Configuration();
    }

    /**
     * 解析 SqlMapConfig
     */
    public Configuration parse() throws Exception {
        Properties properties = new Properties();
        try {
            // SqlMapConfig.xml解析
            Document document = new SAXReader().read(inputStream);
            Element rootElement = document.getRootElement();
            List<Element> nodes = rootElement.selectNodes("//property");
            for (Element element : nodes) {
                String key = element.attributeValue("name");
                String value = element.attributeValue("value");
                properties.setProperty(key, value);
            }
            // 设置二级缓存
            List<Element> cacheList = rootElement.selectNodes("//cache");
            if (cacheList!= null && cacheList.size() > 0) {
                Element element = cacheList.get(0);
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                // 通过反省给cacheEnabled赋值
                PropertyDescriptor descriptor = new PropertyDescriptor(name, configuration.getClass());
                Method method = descriptor.getWriteMethod();
                method.invoke(configuration, Boolean.valueOf(value));
                if (configuration.getCacheEnabled()) {
                    configuration.setStatementCache(new HashMap<>());
                }
            }
            //mapper.xml解析: 拿到路径--字节输入流---dom4j进行解析
            List<Element> mapperList = rootElement.selectNodes("//mapper");
            for (Element element : mapperList) {
                String mapperPath = element.attributeValue("resource");
                InputStream inputStream = Resources.getResourceAsStream(mapperPath);
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
                xmlMapperBuilder.parse(inputStream);
            }
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
        try {
            // comboPool连接池 创建数据源
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
            comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
            comboPooledDataSource.setUser(properties.getProperty("username"));
            comboPooledDataSource.setPassword(properties.getProperty("password"));
            comboPooledDataSource.setAcquireRetryAttempts(Integer.valueOf(properties.getProperty("acquireRetryAttempts"))==null?
                    1 : Integer.valueOf(properties.getProperty("acquireRetryAttempts")));
            configuration.setDataSource(comboPooledDataSource);
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error creating dataSource. Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
        return configuration;
    }

}
